const { extend, Toast } = require('../../zanui/index')
import { HOST } from '../../config/apiConfig.js'
import { obj2Form } from '../../utils/util.js'

//获取应用实例
const app = getApp()

Page(extend({}, Toast, {
  data: {
    userInfo: {},
    areaInfo: {},
    position: [],
    areaList: []
  },
  bindAreaChange: function (e) {
    app.globalData.areaInfo = this.data.areaList[e.detail.value]
    this.setData({
      areaInfo: this.data.areaList[e.detail.value]
    })
  },
  bindSubmit: function () {
    const _self = this
    wx.showLoading({
      title: '加载中',
    })
    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: HOST + '/v1/weChatOpenid/' + res.code,
            success: (res) => {
              if (res.statusCode == 200 && res.data.code == '000000') {
                // 设置全局openId
                app.globalData.userInfo.openid = res.data.data
                _self.checkUserPremission()
              }
            }
          })
        }
      },
      fail: function (res) {
        wx.hideLoading()
        _self.showZanToast('微信登录失败,请稍后再试')
      },
      complete: function () {
        wx.hideLoading()
      }
    })
  },
  checkUserPremission(){
    const _self = this
    // 请求用户是否存在,如果不存在则添加用户,如果存在则判断用户权限
    wx.request({
      url: HOST + '/v1/weChatUser/' + app.globalData.userInfo.openid,
      success: (res) => {
        const data = res.data.data
        if(data != null){
          app.globalData.userInfo.userType = data.userType
        }
        if (data == null) {
          // 注册用户,并告知用户无权限
          const user = {}
          user.openid = app.globalData.userInfo.openid
          user.nickname = app.globalData.userInfo.nickName
          user.headerUrl = app.globalData.userInfo.avatarUrl
          wx.request({
            url: HOST + '/v1/weChatUser',
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data: obj2Form(user),
            method: 'POST',
            success: (res) => {
              // 注册成功后再次检查用户权限
              _self.checkUserPremission()
              return;
            }
          })
        } else if (data.userType == 0) {
          wx.hideLoading()
          _self.showZanToast("当前用户暂无权限,请联系管理员开通权限")
        } else if (data.userType == 1 || data.userType == 2) {
          wx.hideLoading()
          wx.navigateTo({
            url: '../home/home',
          })
        }
      },
      fail: function(){
        _self.showZanToast("鉴权失败,请稍后重试")
        wx.hideLoading()
      },
      complete: function(){
        wx.hideLoading()
      }
    })
  },
  onLoad: function () {
    // 获取用户信息
    if (app.globalData.userInfo.nickName != undefined) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo
          })
        }
      })
    }
    // 获取地址信息
    this.getPosition()
  },
  getUserInfo: function (e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  getPosition: function () {
    // 获取定位信息
    const _self = this
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        app.globalData.position = [res.latitude, res.longitude]
        _self.setData({
          position: [res.latitude, res.longitude]
        })
        // 获取经纬度成功过后再请求数据
        _self.getAreaList()
      }
    })
  },
  getAddressInfo: function () {
    // 根据经纬度获取地址信息
    if (this.data.position.length != 2) {
      return
    }
    const _self = this
    app.globalData.QQMap.reverseGeocoder({
      location: {
        latitude: _self.data.position[0],
        longitude: _self.data.position[1]
      },
      success: function (res) {
        let tmpArea = _self.data.areaList[0]
        if (res.status == 0) {
          const area = res.result.address_component.district
          const obj = _self.data.areaList.find(o => area.indexOf(o.name) > -1)
          if (obj != null) {
            tmpArea = obj
          }
        }
        app.globalData.areaInfo = tmpArea
        _self.setData({
          areaInfo: tmpArea
        })
      }
    })
  },
  getAreaList() {
    const _self = this
    wx.request({
      url: 'https://qdndc.ideatower.cn/v1/address',
      method: 'GET',
      success: function (res) {
        if (res.statusCode != 200) {
          _self.showZanToast('请求接口失败')
          return
        }
        if (res.data.code != '000000') {
          _self.showZanToast(res.data.message)
          return
        }
        _self.setData({
          areaList: res.data.data
        })
        _self.getAddressInfo()
      },
      fail: function () {
        _self.showZanToast('网络错误')
      }
    })
  },
  onPullDownRefresh(){
    wx.stopPullDownRefresh()
  }
}))
